'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 登陆服务器
 * @author sundbcn@gmail.com (sun debing)
 */

var _ = require('lodash');
var async = require('async');
var moment = require('moment');
var Code = require('../../../consts/code');
var moduleType = require('../../../consts/moduleType');
var operationType = require('../../../consts/operationType');
var roleModel = require('../../../models/roleModel');
var skillModel = require('../../../models/skillModel');
var bagModel = require('../../../models/bagModel');
var userModel = require('../../../models/userModel');
var soldierModel = require('../../../models/soldierModel');
var jobType = require('../../../consts/jobType');
var dataApi = require('../../../libs/dataApi');
var skillConf = require('../../../config/skillConf');
var analyze = require('../../../libs/analyze');
var playerManager = require('../../../libs/playerManager');
var rewardService = require('../../../services/rewardService');
var filterSensitiveService = require('../../../services/filterSensitiveService');

module.exports = function (app) {
    return new Handler(app);
};

var Handler = function (app) {
    this.app = app;
};

/**
 * 创建角色
 */
Handler.prototype.createRole = function (msg, session, next) {
    var auth_uid = session.get('auth_uid');
    var job_type = msg.job_type;
    var name = msg.name;
    var channel_id = session.get('channel_id');

    if (!auth_uid) {
        return next(null, {
            code: Code.ENTRY_AUTH_UID_NOT_FOUND
        });
    }

    if (!job_type || job_type < jobType.WARRIOR || job_type > jobType.MASTER || !name) {
        return next(null, {
            code: Code.PARAM_ERROR
        });
    }

    var role_model;

    var role_id;
    var player_manager;
    async.waterfall(
        [
            function (cb) {
                // 检测名字是否含有敏感词
                if (!filterSensitiveService.detect(name)) {
                    return next(null, {
                        code: Code.ROLE_NAME_CONTAIN_SENSITIVE
                    });
                }
                // 判断是否包含特殊符号
                if (_containtInvalidChar(name)) {
                    return next(null, {
                        code: Code.ROLE_NAME_CONTAIN_INVALID_CHAR
                    });
                }
                roleModel.getByName(name, cb);
            },
            function (model, cb) {
                // 判断是否有重复的名字
                if (!!model) {
                    return next(null, {
                        code: Code.ROLE_NAME_IS_EXIST
                    });
                }

                roleModel.getByJob(auth_uid, job_type, cb);
            },

            function (model, cb) {
                if (!!model) {
                    return next(null, {
                        code: Code.ROLE_JOB_IS_EXIST
                    });
                }

                roleModel.createRole(auth_uid, channel_id, job_type, name, cb);
            },
            function (model, cb) {
                role_model = model;
                if (!model) {
                    return next(null, {
                        code: Code.ROLE_CREATE_FAIL
                    });
                }

                role_id = role_model.getRoleId();
                player_manager = new playerManager(role_id);
                player_manager.getModel(
                    ['role', 'build', 'skill', 'soldier', 'bag', 'accrued', 'check'],
                    cb
                );
            },
            function (cb) {
                var skill_model = player_manager.skill;
                var soldier_model = player_manager.soldier;
                var check_model = player_manager.check;

                // 初始化技能
                _initSkill(skill_model, job_type);

                // 初始化士兵
                _initSoldier(soldier_model, job_type);

                // 初始化背包
                _initBag(player_manager, job_type);

                // 初始化不可签到天数
                _initDenyCheckDay(check_model);

                cb();
            },
            function (cb) {
                player_manager.save(cb);
            }
        ],
        function (err) {
            console.log('-----create role end-------');
            if (!!err) {
                console.error('---创建失败', err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            _analyzeRegister(role_id, auth_uid, name, channel_id, '0.0.0.0');
            return next(null, {
                code: Code.OK,
                result: {
                    role_id: role_id
                }
            });
        }
    );
};

/**
 * 角色列表
 */
Handler.prototype.list = function (msg, session, next) {
    var role_id = session.uid;
    var auth_uid = session.get('auth_uid');

    var role_list;
    var last_login_job_type;
    async.waterfall(
        [
            function (cb) {
                if (!!role_id) {
                    session.unbind(role_id, cb);
                } else {
                    cb();
                }
            },
            function (cb) {
                _getRoleList(auth_uid, cb);
            },
            function (result, cb) {
                role_list = result;
                userModel.getByUid(auth_uid, cb);
            },
            function (user_model, cb) {
                last_login_job_type = user_model.getLastLoginJobType();
                cb();
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            return next(null, {
                code: Code.OK,
                result: {
                    role_list: role_list,
                    last_login_job_type: last_login_job_type
                }
            });
        }
    );
};

/**
 * 初始化职业技能
 */
var _initSkill = function (skill_model, job_type) {
    var select_skill_list = skillConf.getJobCanOpenSkillList(job_type, 1);
    _.each(select_skill_list, function (skill_id) {
        skill_model.addSkill(skill_id);
    });
};

/**
 * 初始化职业背包
 */
var _initBag = function (player_manager, job_type) {
    var bag_model = player_manager.bag;
    var role_model = player_manager.role;

    // 初始装备
    var hero_conf = dataApi.hero_type.findById(job_type);
    var initial_equipment_list = hero_conf.initial_equipment.split(',');
    _.each(initial_equipment_list, function (equip_type) {
        bag_model.addEquip(equip_type, true);
    });
    var equip_list = bag_model.getEquipList();
    _.each(equip_list, function (equip_item) {
        bag_model.equip(equip_item.getId());
    });

    // 初始背包物品
    var reward_list = dataApi.start_bag.findById(role_model.getJob());
    rewardService.addRewardListToRole(player_manager, reward_list, moduleType.MDL_OTHER, operationType.OPR_OTHER_CREATE_ROLE);
};

/**
 * 初始化兵种
 */
var _initSoldier = function (soldier_model, job_type) {
    var hero_conf = dataApi.hero_type.findById(job_type);
    var initial_soldier_list = hero_conf.initial_soldier.split(',');
    _.each(initial_soldier_list, function (soldier_type) {
        soldier_model.addSoldier(soldier_type);
    });
};

var _getRoleList = function (auth_uid, next) {
    var role_equip_list = [];
    async.waterfall([
        function (cb) {
                roleModel.getRoleList(auth_uid, cb);
        },
        function (result, cb) {
                var role_list = result;
                async.forEach(role_list, function (role_item, cb1) {
                        bagModel.getByRoleId(role_item.role_id, function (err, bag_model) {
                            var role_info = role_item;
                            role_info.equip_list = _toEquipTypeList(bag_model.getWearEquipList());
                            role_equip_list.push(role_info);
                            cb1();
                        });
                    },
                    function (err) {
                        cb();
                    });
        }],
        function (err) {
            if (!!err) {
                return next(null);
            }
            return next(null, role_equip_list);
        }
    );
};

/**
 * 获取装备的属性
 * @param  {[type]} bag_model [description]
 * @return {[type]}           [description]
 */
var _toEquipTypeList = function (wear_equip_list) {
    var equip_type_list = [];
    _.each(wear_equip_list, function (equip_item) {
        equip_type_list.push(equip_item.getType());
    });
    return equip_type_list;
};

/**
 * 统计注册
 * @param  {[type]} role_id [description]
 * @return {[type]}         [description]
 */
var _analyzeRegister = function (role_id, uid, name, channel_id, create_ip) {
    analyze.recordRegister(role_id, uid, name, channel_id, create_ip);
};

/**
 * 判断角色名是否包含无效符号
 * @param  {[type]} role_id [description]
 * @return {[type]}         [description]
 */
var _containtInvalidChar = function (name) {
    var cr = String.fromCharCode(13);
    var cn = String.fromCharCode(10);
    return (name.indexOf(cr) >= 0) || (name.indexOf(cn) >= 0);
};

// 初始化不可签到天数
var _initDenyCheckDay = function (check_model) {
    var curr_day = parseInt(moment().format('D'));
    check_model.deny_check_day = curr_day - 1;
    check_model.last_refresh_time = Date.now();
};
